import React, { Component } from 'react';
import CustomForm from '../../../components/CustomForm';
import { Input, message } from 'antd';
import services from '../../../services/api';

class PermissionAdd extends Component {
  constructor(props) {
    super(props);
    this.state = {
      treeData: [],
      detail: {}
    };
    this.actionType = 'add';
    this.form = null;
    this.api = 'permission';
  }

  componentDidMount() {
    if (this.props.actionType) {
      if (this.actionType === 'update') {
        this.id = this.props.record.id;
        this.getDetail();
      }
    }
  }

  getDetail = () => {
    services[this.api].queryOne({ id: this.id }).then(data => {
      if (data.code === 0) {
        this.setState({
          detail: data.data
        });
        this.form.setFieldsValue({
          name: data.data.name,
          remark: data.data.remark
        });
      } else {
        message.error(data.msg);
      }
    });
  };

  handleSubmit = () => {
    this.form.validateFields((err, values) => {
      if (!err) {
        const params =
          this.actionType === 'add'
            ? {
                name: values.name,
                remark: values.remark
              }
            : {
                id: this.state.detail.id,
                name: values.name,
                remark: values.remark
              };
        services[this.api][this.actionType](params).then(data => {
          if (data.code === 0) {
            message.success('操作成功');
            if (this.props.closeModal) {
              this.props.closeModal();
            }
          } else {
            message.error(data.msg);
          }
        });
      }
    });
  };

  render() {
    this.actionType = this.props.actionType;
    const { name, remark } = this.props.record || {};

    const formItems = [
      {
        label: {
          label: '权限',
          className: 'tantuer-form-item4 tantuer-form-item-nowrap'
        },
        name: 'name',
        options: {
          initialValue: name,
          rules: [
            { required: true, message: '请输入权限' },
            { max: 128, message: '最长128个字符' },
            { pattern: /^[\u4E00-\u9FA5_a-zA-Z0-9]+$/, message: '限中英文数字下划线' }
          ]
        },
        component: <Input placeholder='权限' />
      },
      {
        label: {
          label: '备注',
          className: 'tantuer-form-item4 tantuer-form-item-nowrap'
        },
        name: 'remark',
        options: {
          initialValue: remark,
          rules: [
            { max: 256, message: '最长256个字符' }
          ]
        },
        component: <Input.TextArea placeholder='备注' />
      }
    ];

    return (
      <CustomForm
        {...this.props}
        closeModal={this.props.closeModal}
        createForm={ref => (this.form = ref)}
        formItems={formItems}
        onHandleSubmit={this.handleSubmit}
        colNum={1}
      />
    );
  }
}

export default PermissionAdd;
